package com.vinoxm.rss.service;

import com.vinoxm.common.base.result.BaseResult;
import com.vinoxm.common.base.result.DataResult;
import com.vinoxm.common.core.service.BaseService;
import com.vinoxm.common.utils.StringUtils;
import com.vinoxm.rss.dao.RssDao;
import com.vinoxm.rss.dao.RssDetailDao;
import com.vinoxm.rss.model.RssDetail;
import com.vinoxm.rss.redis.RedisClient;
import lombok.Setter;

import javax.annotation.Resource;

public class RssDetailService<T extends RssDetailDao, U extends RssDetail> extends BaseService<T> {

    @Setter(onMethod_ = @Resource)
    private RssDao rssDao;

    public BaseResult getManyByPid(Long pid) {
        return DataResult.Success(baseDao.selectByPid(pid));
    }

    public BaseResult editOne(U rssDetail) {
        int count = baseDao.updateOne(rssDetail);
        flushSeason(count, rssDetail.getPid());
        return count == 1 ? BaseResult.Success() : BaseResult.Failed("修改失败");
    }

    public BaseResult addOne(U rssDetail) {
        int count = baseDao.insertOne(rssDetail);
        flushSeason(count, rssDetail.getPid());
        return count == 1 ? BaseResult.Success() : BaseResult.Failed("添加失败,已存在");
    }

    private void flushSeason(int count, Long pid) {
        if (count == 1) {
            String season = rssDao.selectRssSubscribeSeasonById(pid);
            if (!StringUtils.isEmpty(season)) RedisClient.removeRssSubsBySeason(season);
        }
    }

    public BaseResult delOne(Long id) {
        Long pid = baseDao.selectPidById(id);
        flushSeason(baseDao.deleteOne(id), pid);
        return BaseResult.Success();
    }

    public BaseResult delManyByPid(Long pid) {
        flushSeason(baseDao.deleteManyByPid(pid), pid);
        return BaseResult.Success();
    }

}
